package sample.chapter7.searching;

import java.util.Arrays;
import java.util.Comparator;

/**
 * A sample class demonstrating
 * <p>
 * 1. How to do inverse sorting<p>
 * 2. How the <code>Arrays.binarySearch()</code> leverage a <code>Comparator</code>
 * 3. How the (-(insertion_position)-1) rule gets applied
 *  
 * @author kan.sun
 *
 */
public class SearchObjectArray
{
	public static void main(String[] args)
	{
		String[] sa = {"one", "two", "three", "four"};
		Arrays.sort(sa);
		System.out.println("Sorted string: ");
		for(String s:sa)
			System.out.print(s+" ");
		System.out.println("\none = "+Arrays.binarySearch(sa, "xfire"));
		
		ResortComparator rs = new ResortComparator();
		Arrays.sort(sa, rs);
		System.out.println("Resorted string: ");
		for(String s:sa)
			System.out.print(s+" ");
		System.out.println("\none = "+Arrays.binarySearch(sa, "us"));
		System.out.println("one = "+Arrays.binarySearch(sa, "us", rs));
	}
	
	static class ResortComparator implements Comparator<String>
	{
		@Override
		public int compare(String o1, String o2)
		{
			return -o1.compareTo(o2);
		}
	}
}
